package controllers

import (
	cap "github.com/dchest/captcha"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"net/http"
	"testGin/model/core"
	"testGin/model/mysql"
	"testGin/model/tool"
)

type IndexController struct{}

func (ctl IndexController) InfoAjax(c *gin.Context)  {

	adminInfo := mysql.AdminInfo{}

	if errs :=c.Bind(&adminInfo); errs != nil {
		tool.Error(c,0 ,errs.Error())
		return
	}

	err := mysql.AdminInfo{}.SaveItem(&adminInfo)

	if err != nil {
		tool.Error(c,0 ,err.Error())
		return
	}

	tool.Success(c,200,"修改成功",adminInfo)
}

func (ctl IndexController) Info(c *gin.Context) {

	info := mysql.AdminInfo{}.GetItem()
	c.Bind(&info)
	c.HTML(http.StatusOK, "system/index/info.html", gin.H{
		"item":info,
	})
}


func (ctl IndexController) Init(c *gin.Context) {

	 admin := tool.SessionGet(c,"admin");
	 config:= core.Cuser{}.GetAdminNodes(admin.(mysql.Admins).Id)
	 c.JSON(200,config)

}

func (ctl IndexController) Index(c *gin.Context) {
	ctl.Login(c)
}

func (ctl IndexController) Login(c *gin.Context) {

	infos := mysql.AdminInfo{}
	item := infos.GetItem()
	c.HTML(http.StatusOK, "system/index/login.html", gin.H{
		"title": item.Sitename,
	})
}

func (ctl IndexController) Show(c *gin.Context) {

	admin := tool.SessionGet(c,"admin");

	infos := mysql.AdminInfo{}

	item := infos.GetItem()

	c.HTML(http.StatusOK, "system/index/index.html", gin.H{
		"title":item.Sitename,
		"admin": admin.(mysql.Admins).Account,
	})
}
func (ctl IndexController) Console(c *gin.Context) {

	c.HTML(http.StatusOK, "system/index/console.html", gin.H{})
}

func (ctl IndexController) LoginAjax(c *gin.Context) {

	account := c.PostForm("account")
	password := c.PostForm("password")
	captcha := c.PostForm("captcha")
	session := sessions.Default(c)
	if captchaId := session.Get("code"); captchaId != nil {
		if cap.VerifyString(captchaId.(string), captcha) {

		} else {
			tool.Error(c,0,"验证码不正确")
			return
		}
	} else {
		tool.Error(c,0,"验证码已过期")
		return
	}

	res := core.Cuser{}.Login(c,account,password)

	if res.Code == 1 {
		tool.Success(c,200,"登录成功","")
	}else{
		tool.Error(c,0,res.Msg)
	}
}

func (ctx IndexController) Logout(c *gin.Context){

	token := tool.SessionGet(c,"token")
	core.Cuser{}.LoginOut(c,token.(string));
	tool.Success(c,200,"退出成功","")
}
